package com.lily.ssm.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lily.ssm.model.News;
import com.lily.ssm.model.Pager;
import com.lily.ssm.model.Product;
import com.lily.ssm.model.ProductClass;
import com.lily.ssm.service.NewsService;

@Controller
public class NewsController {
	@Autowired
	private NewsService newsService;
	
	@RequestMapping("/selectNews.do")
	public String newsList(Pager<News> pager,Model model){
		//将每页显示的默认数据修改成5
		pager.setPageSize(5);
		// 分页查询数据
		List<News> news = newsService.selectNews(pager.getOffset());
	 	// 查询共有News多少条数据，存入Pager中
		pager.setCount(newsService.getNewsCount());
		// 判断接受的pageIndex是否为0，为0的话赋予默认值1
		int index = pager.getPageIndex();
		index = index == 0 ? 1 : index;
		// 将返回的pagerIndex存入pager中
		pager.setPageIndex(index);
		// 将分页查询的数据存入pager中
		pager.setDatas(news);
		// 将pager传到页面
		model.addAttribute("pager", pager);
		return "manage/news";
	}
	
	@RequestMapping(value="/addNews.do",method=RequestMethod.GET)
	public String addNews(){
		
		return "manage/news-add";
	}
	
	@RequestMapping(value="/addNews.do",method=RequestMethod.POST)
	public String addNews(News news){
		Date date = new Date();
		news.setReleaseTime(date);
		newsService.insertNews(news);
		return "redirect:/selectNews.do";
	}
	
	@RequestMapping(value="/updateNews.do",method=RequestMethod.GET)
	public String updateNews(int newsId,Model model){
		News news = newsService.getNews(newsId);
		model.addAttribute("news", news);
		return "manage/news-modify";
	}
	
	@RequestMapping(value="/updateNews.do",method=RequestMethod.POST)
	public String updateNews(News news,int newsId){
		news.setNewsId(newsId);
		Date date = new Date();
		news.setReleaseTime(date);
		newsService.updateNews(news);
		return "redirect:/selectNews.do";
	}
	
	@RequestMapping("/deleteNews.do")
	public String deleteNews(int newsId,int pageIndex){
		System.out.println(pageIndex);
		newsService.deleteNews(newsId);
		return "redirect:/selectNews.do";
	}
}
